<template>
  <div>
    <el-form :inline="true" :model="searchForm" @keyup.enter.native="pageIndex = 1;getDataList()">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="商品名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.categoryId" clearable filterable placeholder="商品分类"
                   class="width185">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.isOnSale" clearable placeholder="上架">
          <el-option
            key="0"
            label="下架"
            value="0">
          </el-option>
          <el-option
            key="1"
            select="select"
            label="上架"
            value="1">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="pageIndex = 1; getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="showSelectList()">查看已选</el-button>
      </el-form-item>
    </el-form>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100, 200]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <el-table
      :data="dataList"
      @sort-change="sortHandle"
      border
      style="width: 100%">
      <el-table-column
        width="150"
        prop="name"
        header-align="center"
        align="center"
        label="商品名称">
      </el-table-column>
      <el-table-column
        width="150"
        prop="categoryName"
        header-align="center"
        align="center"
        label="类型">
      </el-table-column>
      <el-table-column
        prop="listPicUrl"
        header-align="center"
        align="center"
        label="列表图">
        <template slot-scope="scope">
          <img style="height: 50%;width: 50%" @click="openImg(scope.row.listPicUrl)" :src="scope.row.listPicUrl"/>
        </template>
      </el-table-column>
      <el-table-column
        show-tooltip-when-overflow
        prop="goodsBrief"
        header-align="center"
        align="center"
        label="简明介绍">
      </el-table-column>
      <el-table-column
        prop="branchIntegral"
        header-align="center"
        align="center"
        sortable="custom"
        label="积分">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('mall:goods:info')" type="text" size="small" @click="showDetails(scope.row.id)">查看
          </el-button>
          <el-button v-if="isAuth('mall:goods:info')" type="text" size="small"
                     @click="selectHandle(scope.row.id, scope.row.name, scope.row.branchIntegral )">选择商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100, 200]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <el-dialog
      title="已选商品"
      :visible.sync="dialogVisible"
      width="40%"
      append-to-body
    >
      <el-table
        :data="selectList"
        border
        :summary-method="getSummaries"
        show-summary
        style="width: 100%">
        <el-table-column
          width="150"
          prop="goodsName"
          header-align="center"
          align="center"
          label="商品名称">
        </el-table-column>
        <el-table-column
          width="150"
          prop="integral"
          header-align="center"
          align="center"
          label="积分">
        </el-table-column>
        <el-table-column
          width="190"
          prop="number"
          header-align="center"
          align="center"
          label="数量">
          <template slot-scope="scope">
            <el-input-number :min="1" size="small" v-model="scope.row.number"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          width="80">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="20">
        <el-col :span="12" :offset="14">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" v-if="this.selectList.length > 0" @click="dataFormSubmit()">确 定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      title="选择商品"
      :visible.sync="selectVisible"
      width="30%"
      append-to-body
    >
      <el-form :model="dataForm" ref="dataForm" @keyup.enter.native="selectAddHandle()" label-width="80px">
        <el-form-item label="商品名" prop="goodsName">
          <el-input v-model="dataForm.goodsName" :disabled="true" placeholder="商品名"></el-input>
        </el-form-item>
        <el-form-item label="积分" prop="integral">
          <el-input v-model="dataForm.integral" :disabled="true" placeholder="积分"></el-input>
        </el-form-item>
        <input type="hidden" v-model="dataForm.orgNo"></input>
        <input type="hidden" v-model="dataForm.goodsId"></input>
        <el-form-item label="数量" prop="number">
          <el-input-number :min="1" size="small" v-model="dataForm.number" placeholder="数量"></el-input-number>
        </el-form-item>
      </el-form>
      <el-row :gutter="20">
        <el-col :span="12" :offset="14">
          <el-button @click="selectVisible = false">取 消</el-button>
          <el-button type="primary" @click="selectAddHandle()">确 定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<css>
.demo-drawer{
overflow:auto
}

</css>

<script>
import AddOrUpdate from './goods-add-or-update'

export default {
  data() {
    return {
      drawer: false,
      dialogVisible: false,
      selectVisible: false,
      direction: 'rtl',
      searchForm: {
        name: '',
        categoryId: '',
        goodsSn: '',
        isOnSale: '1'
      },
      dataList: [],
      dataForm: {
        goodsName: '',
        goodsId: '',
        integral: 0,
        orgNo: '',
        number: 1
      },
      selectList: [],
      sumPrice: 0,
      categoryList: [],
      selectIdList: [],
      selectPageList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListSelections: [],
      addOrUpdateVisible: false,
      goodsskuAddOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDataList()
    this.getCategoryList()
  },
  methods: {
    init() {
      this.drawer = true
      this.getDataList()
    },
    getCategoryList () {
      this.$http({
        url: '/mall/category/queryAllSimple',
        method: 'get',
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.categoryList = data.list
        } else {
          this.categoryList = []
        }
      })
    },
    // 获取数据列表
    getDataList() {
      this.$http({
        url: '/mall/goods/list',
        method: 'get',
        params: {
          'page': this.pageIndex,
          'limit': this.pageSize,
          'name': this.searchForm.name,
          'categoryId': this.searchForm.categoryId,
          'goodsSn': this.searchForm.goodsSn,
          'isOnSale': this.searchForm.isOnSale
        }
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
      })

      this.$http({
        url: '/sys/orggoods/queryAll',
        method: 'get',
        params: {
          'orgNo': JSON.parse(sessionStorage.getItem('userInfo') || '{}').orgNo
        }
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.selectList = data.list
          for (let i = 0; i < this.selectList.length; i++) {
            this.selectIdList.push(this.selectList[i].goodsId)
          }
        } else {
          this.selectList = []
          this.this.selectIdList = []
        }
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    handleClose() {
      this.drawer = false
    },
    sortHandle(val) {
      console.log(val.order)
      console.log(val.prop)
    },
    // 查看详情
    showDetails(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, true)
      })
    },
    // 选择商品
    selectHandle(goodsId, goodsName, integral) {
      this.dataForm = {
        goodsName: goodsName,
        goodsId: goodsId,
        integral: integral,
        orgNo: JSON.parse(sessionStorage.getItem('userInfo') || '{}').orgNo,
        number: 1
      }
      this.selectVisible = true
    },
    selectAddHandle() {
      // 查看商品是否已选择
      let index = this.selectIdList.indexOf(this.dataForm.goodsId)
      if (index > -1) {
        this.selectList.splice(index, 1)
        this.selectIdList.splice(index, 1)
      }
      // 放2个数组，一个是商品，一个是商品id用来判断是否重复选择
      this.selectIdList.push(this.dataForm.goodsId)
      this.selectList.push(this.dataForm)
      this.dataForm = {
        goodsName: '',
        goodsId: '',
        integral: 0,
        orgNo: '',
        number: 1
      }
      this.selectVisible = false
    },
    handleDelete(index, row) {
      this.$confirm(`确定删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectList.splice(index, 1)
      }).catch(() => {
      })
    },
    showSelectList() {
      this.dialogVisible = true
    },
    // 表单提交
    dataFormSubmit() {
      if (this.selectList.length < 1) {
          return
      }
      this.$http({
        url: `/sys/orggoods/addList`,
        method: 'post',
        data: this.selectList
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dialogVisible = false
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500
          })
        }
      })
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 3) {
          let sum = 0
          for (let i = 0; i < data.length; i++) {
            sum += (Number(data[i].number) * Number(data[i].integral))
          }
          sums[index] = sum.toFixed(2)
          this.sumPrice = sums[index]
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    }
  }
}
</script>
